//
//  AMBucketsTableView.m
//  AWSMobile
//
//  Created by James on 14-10-31.
//  Copyright (c) 2014年 Siemens. All rights reserved.
//

#import "AMBucketsTableView.h"
#import "AMConstants.h"
#import <AWSiOSSDKv2/AWSS3.h>
#import <Bolts/BFTask.h>
#import <Bolts/BFExecutor.h>

#import "AMBucketObjectsTableView.h"
#import "AMFunctions.h"
#import "AMBucketCell.h"

@interface AMBucketsTableView ()

@property (nonatomic) NSArray *allBuckets;
@property NSMutableArray *sectionIndexTitle;
@property (nonatomic) AWSRequest *listBucketsRequest;

@end

@implementation AMBucketsTableView

#pragma mark - Setter and getter
- (NSArray *)allBuckets
{
    return _allBuckets;
}

#pragma mark - Life cycle

- (void)viewWillAppear:(BOOL)animated
{
    [self refreshBuckets:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    if (_listBucketsRequest)
    {
        [_listBucketsRequest cancel];
        _listBucketsRequest = nil;
    }
    self.navigationItem.rightBarButtonItem = _refreshButton;
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.sectionIndexTitle = [[NSMutableArray alloc] initWithCapacity:1];
    self.tableView.sectionIndexBackgroundColor = [UIColor clearColor];
    self.tableView.sectionIndexColor = [UIColor colorWithHexString:@"73b89e"];
    [self.tabBarController.tabBar setSelectedImageTintColor:[UIColor colorWithHexString:@"36b2af"]];
    
    UIView *view = [[UIView alloc] init];
    [self.tableView setTableFooterView:view];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.allBuckets.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[self.allBuckets objectAtIndex:section] count];
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return self.sectionIndexTitle;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"BucketCell";
    AMBucketCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    AWSS3Bucket *bucket = [[_allBuckets objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    cell.bucketName.text = bucket.name;
    cell.bucketIcon.image = [UIImage imageNamed:@"文件夹.png"];
    cell.bucketIndicatorColor.backgroundColor = [UIColor randomIndicatorColor];
    
    return cell;
}

#pragma mark - Table view delegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString *bucketName = [[[self.allBuckets objectAtIndex:section] firstObject] name];
    return [[bucketName substringToIndex:1] uppercaseString];
}

#pragma mark - Segue
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    NSIndexPath *selected = [self.tableView indexPathForCell:sender];
    AMBucketObjectsTableView *view = (AMBucketObjectsTableView *)segue.destinationViewController;
    view.bucketName = [[[self.allBuckets objectAtIndex:selected.section] objectAtIndex:selected.row] name];
}

#pragma mark - Actions

- (void)networkStarted
{
    UIActivityIndicatorView *iView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    UIBarButtonItem *iBarItem = [[UIBarButtonItem alloc] initWithCustomView:iView];
    [iView startAnimating];
    self.navigationItem.rightBarButtonItem = iBarItem;
}

- (void)networkStopped
{
    self.navigationItem.rightBarButtonItem = _refreshButton;
}

- (IBAction)refreshBuckets:(UIBarButtonItem *)sender
{
    [self networkStarted];
    if (_listBucketsRequest)
    {
        _listBucketsRequest = [[AWSRequest alloc] init];
    }
    __block typeof(self) weakSelf = self;
    
    [[[AWSS3 defaultS3] listBuckets:_listBucketsRequest] continueWithExecutor:[BFExecutor defaultExecutor] withBlock:^id(BFTask *task){
        if (!task.error)
        {
            __block NSMutableArray *resultDic = [[NSMutableArray alloc] initWithCapacity:1];
            NSArray *buckets = [(AWSS3ListBucketsOutput *)task.result buckets];
            NSMutableArray *containner = [[NSMutableArray alloc] initWithCapacity:1];
            for (AWSS3Bucket *bucket in buckets)
            {
                NSString *first = [[bucket.name substringToIndex:1] uppercaseString];
                NSString *last = [[[[[resultDic lastObject] firstObject] name] substringToIndex:1] uppercaseString];
                if (!last)
                {
                    [containner addObject:bucket];
                    [resultDic addObject:[containner copy]];
                    [weakSelf.sectionIndexTitle addObject:first];
                }
                else if ([last isEqualToString:first])
                {
                    [containner addObject:bucket];
                }
                else
                {
                    resultDic[resultDic.count - 1] = [containner copy];
                    [containner removeAllObjects];
                    [containner addObject:bucket];
                    [resultDic addObject:[containner copy]];
                    [weakSelf.sectionIndexTitle addObject:first];
                }
            }
//                NSLog(@"%@",resultDic);
            dispatch_async(dispatch_get_main_queue(), ^{
                weakSelf.allBuckets = resultDic;
                [weakSelf networkStopped];
                [weakSelf.tableView reloadData];
            });
        }
        else
        {
            NSLog(@"buckets error.%@",task.error);
        }
        return nil;
    }];
}
@end
